package com.happyrecyclingstation.controller.websocket;
import com.alibaba.fastjson.JSONObject;
import com.alibaba.fastjson.JSON;
import com.happyrecyclingstation.dto.MessageDto;
import com.happyrecyclingstation.service.MessageService;
import com.happyrecyclingstation.utils.GenerateSessionId;
import jakarta.websocket.OnClose;
import jakarta.websocket.OnMessage;
import jakarta.websocket.OnOpen;
import jakarta.websocket.Session;
import jakarta.websocket.server.PathParam;
import jakarta.websocket.server.ServerEndpoint;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.Map;

/**
 * 聊天接口
 */
@Component
@ServerEndpoint("/ws/{sid}")
public class PrivateChatEndpoint {

    // 静态的MessageService引用
    private static MessageService messageService;

    // 通过setter方法注入MessageService
    @Autowired
    public void setMessageService(MessageService messageService) {
        PrivateChatEndpoint.messageService = messageService;
    }
    // 存储会话对象
    private static Map<String, Session> sessionMap = new HashMap<>();

    @OnOpen
    public void onOpen(Session session, @PathParam("sid") String sid) {
        System.out.println("客户端：" + sid + "建立连接");
        sessionMap.put(sid, session);
    }

    @OnMessage
    public void onMessage(String message, @PathParam("sid") String sid) {
        System.out.println("接收到消息:" + message);
        try {
            JSONObject jsonObject = JSON.parseObject(message);
            Integer receiverId = Integer.valueOf(jsonObject.getString("receiverId"));
            Integer senderId = Integer.valueOf(sid);
            String content = jsonObject.getString("message");
            //保存到数据库
            String sessionId = GenerateSessionId.generateSessionId(senderId, receiverId);
            messageService.saveMessage(new MessageDto(sessionId, senderId, receiverId, content));
            // 只发送给接收方，不发送回发送方
            Session receiverSession = sessionMap.get(receiverId + "");
            if (receiverSession != null) {
                try {
                    JSONObject msgObj = new JSONObject();
                    msgObj.put("senderId", sid);
                    msgObj.put("content", content);
                    msgObj.put("sendTime", LocalDateTime.now());
                    receiverSession.getBasicRemote().sendText(msgObj.toJSONString());
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    @OnClose
    public void onClose(@PathParam("sid") String sid) {
        System.out.println("连接断开:" + sid);
        sessionMap.remove(sid);
    }
}